import React, { useEffect, useState, useCallback } from 'react';
import styles from './index.less';
import { fetchDataPost } from '@/utils/fetch';

const imageApiData = [
  { id: 1, name: '风景图1', url: 'https://picsum.photos/id/10/800/600' },
  { id: 2, name: '城市图1', url: 'https://picsum.photos/id/26/800/600' },
  { id: 3, name: '动物图1', url: 'https://picsum.photos/id/237/800/600' },
  { id: 4, name: '植物图1', url: 'https://picsum.photos/id/106/800/600' },
  { id: 5, name: '人物图1', url: 'https://picsum.photos/id/64/800/600' },
];

interface ProteinCategoryListProps {
  activeCategory: any;
  setActiveCategory: (category: any) => void;
}

// 面包屑项接口
interface BreadcrumbItem {
  id: string | number | null;
  name: string;
  level: number;
}

const ProteinCategoryList: React.FC<ProteinCategoryListProps> = ({
  activeCategory,
  setActiveCategory,
}) => {
  // 一\二级素材
  const [level12Categories, setLevel12Categories] = useState([]);
  // 三级素材
  const [level3Categories, setLevel3Categories] = useState([]);
  // 面包屑状态 - 直接存储面包屑项数组，每项包含完整信息
  const [breadcrumbItems, setBreadcrumbItems] = useState<BreadcrumbItem[]>([
    { id: null, name: '素材', level: 0 },
  ]);

  // 保存当前父级分类名称的状态，确保面包屑始终显示正确的二级分类名称
  const [currentParentName, setCurrentParentName] = useState<string>('');

  // 获取目录
  const getData = (category?: object) => {
    // 默认一级目录
    let params: any = {
      guid: '6084b1f26b234d68b5d4349d9f29b839',
      pageNo: 1,
      pageSize: 50,
      type: 2,
    };
    // 二级目录
    if (category) {
      params = {
        ...params,
        catalogId: activeCategory?.id,
      };
    }
    fetchDataPost(
      'https://gateway.rjmart.cn/base/draw/anno/catalog/page',
      params,
    )
      .then((res) => {
        if (res?.code === 200) {
          setLevel12Categories(res?.data);
        }
      })
      .catch((err) => {
        console.log('err', err);
      });
  };

  // 获取三级目录
  const getThirdData = (category?: object) => {
    let params = {
      catalogId: category?.id,
      pageSize: 100,
      pageNo: 1,
      guid: '6084b1f26b234d68b5d4349d9f29b839',
    };
    fetchDataPost(
      'https://gateway.rjmart.cn/base/draw/anno/picture/pagepublicpic',
      params,
    )
      .then((res) => {
        if (res?.code === 200) {
          console.log('333res', res);
          setLevel3Categories(res?.data);
        }
      })
      .catch((err) => {
        console.log('err', err);
      });
  };

  // 初始化时加载数据
  useEffect(() => {
    getData();
  }, []);

  // 处理activeCategory变化，统一管理数据加载和面包屑更新
  useEffect(() => {
    // 添加日志，帮助调试
    console.log('activeCategory updated:', activeCategory);

    // 清空当前数据
    setLevel12Categories([]);
    setLevel3Categories([]);

    // 根据activeCategory的level决定当前层级和要加载的数据
    if (!activeCategory || Object.keys(activeCategory).length === 0) {
      // 一级目录（根目录）
      getData();
      // 重置面包屑为仅包含根节点
      setBreadcrumbItems([{ id: null, name: '素材', level: 0 }]);
      console.log('Set breadcrumb to root level');
    } else if (activeCategory?.level === 1) {
      // 二级目录
      getData(activeCategory);
      // 更新面包屑为根节点 + 当前二级分类
      const level2Breadcrumb = [
        { id: null, name: '素材', level: 0 },
        { id: activeCategory.id, name: activeCategory.name, level: 1 },
      ];
      setBreadcrumbItems(level2Breadcrumb);
      // 保存当前二级分类名称，以便进入三级目录时使用
      setCurrentParentName(activeCategory.name);
      console.log('Set breadcrumb to level 2:', level2Breadcrumb);
    } else if (activeCategory?.level === 2) {
      // 三级目录
      getThirdData(activeCategory);

      // 构建完整的三级面包屑路径
      const newBreadcrumbItems: BreadcrumbItem[] = [
        { id: null, name: '素材', level: 0 },
      ];

      // 优先使用保存的父级名称，其次使用level12Categories中的名称，最后使用默认值
      let secondLevelName =
        currentParentName || activeCategory?.parentName || '二级分类';
      let parentCategoryId = '';

      // 如果有保存的父级名称，尝试从level12Categories中找到对应的ID
      if (currentParentName) {
        const foundCategory = level12Categories?.find(
          (item) => item?.name === currentParentName,
        );
        if (foundCategory) {
          parentCategoryId = foundCategory.id;
        }
      }

      // 添加二级分类（level=1）
      newBreadcrumbItems.push({
        id: parentCategoryId || `parent-${activeCategory.id}`,
        name: secondLevelName,
        level: 1,
      });

      // 添加当前三级分类（level=2）
      newBreadcrumbItems.push({
        id: activeCategory.id,
        name: activeCategory.name,
        level: 2,
      });

      setBreadcrumbItems(newBreadcrumbItems);
      console.log(
        'Set breadcrumb to level 3:',
        newBreadcrumbItems,
        'using parentName:',
        activeCategory?.parentName,
      );
    }
  }, [activeCategory]);

  // 处理面包屑点击事件的通用函数
  const handleBreadcrumbClick = useCallback(
    (breadcrumbItem: BreadcrumbItem) => {
      if (breadcrumbItem.level === 0) {
        // 点击根节点，返回一级目录
        setActiveCategory({});
      } else if (breadcrumbItem.level === 1) {
        // 点击一级分类，返回二级目录
        // 尝试通过ID找到对应的分类
        let targetCategory = null;

        // 如果是从parentName推断的一级分类，通过名称查找
        if (
          typeof breadcrumbItem.id === 'string' &&
          breadcrumbItem.id.startsWith('parent-')
        ) {
          targetCategory = level12Categories?.find(
            (item) => item?.name === breadcrumbItem.name,
          );
        } else {
          // 优先通过ID查找
          targetCategory = level12Categories?.find(
            (item) => item?.id === breadcrumbItem.id,
          );

          // 如果ID查找失败，尝试通过名称查找
          if (!targetCategory) {
            targetCategory = level12Categories?.find(
              (item) => item?.name === breadcrumbItem.name,
            );
          }
        }

        if (targetCategory) {
          setActiveCategory(targetCategory);
        }
      }
      // 对于level2，保持当前状态
    },
    [level12Categories, setActiveCategory],
  );

  return (
    <div className={styles.container}>
      <div className={styles.filterContainer}>
        <select className={styles.select} name="category">
          <option value="all">All</option>
          <option value="Dir">当前目录下</option>
        </select>
        <input className={styles.input} type="search" placeholder="搜索" />
      </div>
      {/* 面包屑导航 */}
      <div className={styles.menuContainer}>
        {breadcrumbItems.map((item, index) => (
          <React.Fragment key={`${item.id}-${item.level}`}>
            {/* 不是第一个元素时显示分隔符 */}
            {index > 0 && ' > '}

            {/* 渲染面包屑链接 */}
            <a
              href=""
              onClick={(e) => {
                e.preventDefault();
                // 只有当点击的不是最后一个元素时才处理点击事件
                if (index < breadcrumbItems.length - 1) {
                  handleBreadcrumbClick(item);
                }
              }}
            >
              {item.name}
            </a>
          </React.Fragment>
        ))}
      </div>
      {level3Categories?.length < 1 && (
        <div className={styles.listContainer}>
          {level12Categories?.map((item) => (
            <div
              key={item?.id}
              className={styles.listItems}
              onClick={() => {
                setActiveCategory(item);
              }}
            >
              <div className={styles.listItemLeft}>
                <img
                  title={item?.chineseName}
                  width={24}
                  height={24}
                  src={item?.thumbnail}
                  alt={item?.chineseName}
                  style={{
                    display: 'block',
                    objectFit: 'contain',
                  }}
                  onError={(e) => {
                    console.error(`图片加载失败: ${item?.thumbnail}`, e);
                    // 如果图片加载失败，可以设置一个占位图
                    const target = e.target as HTMLImageElement;
                    target.src =
                      '';
                  }}
                />
                <div className={styles.textStyle}>{item?.name}</div>
              </div>
              <div className={styles.textStyle}>{'>'}</div>
            </div>
          ))}
        </div>
      )}
      <div className={styles.listContainerL3}>
        {level3Categories?.map((items, index) => {
          // 使用模拟数据中的图片URL
          const imageUrl =
            imageApiData[index % imageApiData.length]?.url ||
            'https://picsum.photos/id/237/800/600';

          return (
            <div key={items?.id} className={styles.listItemL3}>
              <img
                width={68}
                height={56}
                src={imageUrl}
                alt={items?.name || ''}
                draggable={true}
                onDragStart={(e) => {
                  // 设置拖拽数据
                  e.dataTransfer.setData(
                    'application/json',
                    JSON.stringify({
                      id: `image-${items?.id || index}`,
                      type: 'image',
                      name: items?.name || `图片${index + 1}`,
                      imageUrl: imageUrl,
                      color: '#666',
                    }),
                  );
                }}
                style={{
                  cursor: 'grab',
                  border: '1px solid #e8e8e8',
                  borderRadius: '4px',
                }}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default ProteinCategoryList;
